<template>
  <a-layout id="components-layout-demo-top">
    <a-layout-header style="text-align: center">
      <h1 style="color: #fff">在线实时日志</h1>
    </a-layout-header>
    <a-layout-content>
      <div :style="{ background: '#fff', padding: '24px', minHeight: '280px' }">
        <a-card :bordered="false">
          <a-form layout="inline" ref="form" :model="form" label-width="100px">
            <a-form-item label="连接状态">
              <a-tag :color="status.id">
                {{ status.name }}
              </a-tag>
            </a-form-item>
            <a-form-item label="连接地址">
              <a-input v-model="form.url" style="width: 300px"/>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="openSocket">连接</a-button>
            </a-form-item>
          </a-form>
          <a-divider orientation="left">日志详情</a-divider>
          <a-space>
            <a-button value="small" @click="clearLog">清空日志</a-button>
          </a-space>
          <div id="chatContainer"
               style="width:100%;height: 600px;margin-top: 20px;background-color: ghostwhite; overflow: auto"
               v-html="logData">
          </div>
        </a-card>
      </div>
    </a-layout-content>
    <a-layout-footer style="text-align: center">
      SparkZxl ©2021 Created by zhouxinlei
    </a-layout-footer>
  </a-layout>
</template>
<script>
export default {
  name: 'WebSocket',
  components: {},
  data() {
    return {
      webSocket: null,
      logData: '',
      status: {
        id: 'pink',
        name: '关闭'
      },
      form: {url: 'ws://127.0.0.1:8762/websocket/logging'},
    }
  },
  created() {
    this.openSocket()
  },
  destroyed() {
    this.webSocket.close()
  },
  watch: {
    logData() {
      this.$nextTick(() => {
        const container = this.$el.querySelector("#chatContainer");
        container.scrollTop = container.scrollHeight;
      })
    }
  },
  methods: {
    openSocket() {
      const url = this.form.url
      this.webSocket = new WebSocket(url)
      this.webSocket.onmessage = this.onmessage
      this.webSocket.onopen = this.onopen
      this.webSocket.onerror = this.onerror
      this.webSocket.onclose = this.onclose
    },
    onopen() {
      this.status = {
        id: 'green',
        name: '成功'
      }
      this.send('log')
    },
    onerror() {
      this.status = {
        id: 'red',
        name: '失败'
      }
      this.openSocket()
    },
    onmessage({data}) {
      const logData = this.logData;
      this.logData = logData.concat(data)
    },
    send(Data) {
      this.webSocket.send(Data)
    },
    // eslint-disable-next-line no-unused-vars
    onclose(e) {
      this.status = {
        id: 'pink',
        name: '关闭'
      }
    },
    clearLog() {
      this.logData = ''
    },
  },
}
</script>
